let tbody = document.querySelector('tbody')
let addBtn = document.querySelector('.modal-dialog-centered')//添加学员按钮
let addForm = document.querySelector('.add-form')
let province = document.querySelector('[name=province]')// 省
let city = document.querySelector('[name=city]')// 市
let county = document.querySelector('[name=county]')// 区
let name = document.querySelector('[name=name]')
let age = document.querySelector('[name=age]')
let phone = document.querySelector('[name=phone]')
let salary = document.querySelector('[name=salary]')
let truesalary = document.querySelector('[name=truesalary]')
let group = document.querySelector('[name=group]')
let btnAdd = document.querySelector('.modal-dialog-centered')
let addModalLabel = document.querySelector('#addModalLabel')
let btnXg = document.querySelector('.btn-xg')
let addModal = document.querySelector('#addModal form')
let btnCz = document.querySelector('.btn-secondary')
let id = null
let init = () => {
    axios({
        url: '/student/list'
    }).then(({ data }) => {
        let str = ''
        data.forEach((value, index) => {
            str += ` <tr>
                                <th scope="row">${value.id}</th>
                                <td>${value.name}</td >
                                <td>${value.age}</td>
                                <td>${value.sex}</td>
                                <td>${value.group}</td>
                                <td>${value.phone}</td>
                                <td>${value.salary}</td>
                                <td>${value.truesalary}</td>
                                <td>${value.province + value.city + value.county}</td>
                                <td>
                                <button type="button" class="btn btn-primary btn-sm" data-id='${value.id}'>修改</button>
                                <button type="button" class="btn btn-danger btn-sm  delete" data-id='${value.id}'>删除</button>
                                </td>
                      </tr > `
        })
        tbody.innerHTML = str
    })
}
init()
// 验证输入
let student = () => {
    return {
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '姓名不能为空',
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '姓名长度2~10位'
                    }
                }
            },
            age: {
                validators: {
                    notEmpty: {
                        message: '年龄不能为空',
                    },
                    greaterThan: {
                        value: 18,
                        message: '年龄不能小于18岁'
                    },
                    lessThan: {
                        value: 60,
                        message: '年龄不能超过60岁'
                    }
                }
            },
            sex: {
                validators: {
                    choice: {
                        min: 1,
                        max: 1,
                        message: '请选择性别'
                    }
                }
            },
            group: {
                validators: {
                    notEmpty: {
                        message: '组号不能为空',
                    },
                    regexp: {
                        regexp: /^\d{1,2}$/,
                        message: '请选择有效的组号'
                    }
                }
            },
            phone: {
                validators: {
                    notEmpty: {
                        message: '手机号不能为空',
                    },
                    regexp: {
                        regexp: /^1\d{10}$/,
                        message: '请填写有效的手机号'
                    }
                }
            },
            salary: {
                validators: {
                    notEmpty: {
                        message: '实际薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '期望薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '期望薪资不能高于100000'
                    }
                }
            },
            truesalary: {
                validators: {
                    notEmpty: {
                        message: '实际薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '实际薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '实际薪资不能高于100000'
                    }
                }
            },
            province: {
                validators: {
                    notEmpty: {
                        message: '省份必填',
                    },
                }
            },
            city: {
                validators: {
                    notEmpty: {
                        message: '市必填',
                    },
                }
            },
            county: {
                validators: {
                    notEmpty: {
                        message: '县必填',
                    },
                }
            },
        }
    }
}
// 发起添加修改学生函数
let addition = (url, method, id) => {
    let data = {}
    if (id) data.id = id
    let formdata = new FormData(addForm)
    formdata.forEach((value, index) => data[index] = value)
    axios({
        url: url,
        method: method,
        data
    }).then(data => {
        if (data.code == 0) {
            init()
            toastr.success(data.message)
            $('#addModal').modal('hide')
        } else {
            toastr.error(data.message)
        }
    })
}
// 添加按钮
$('#addModal form').bootstrapValidator(student()).on('success.form.bv', function (e) {
    e.preventDefault();
    if (id) {
        addition('/student/update', 'PUT', id)
        id = null
        return
    }
    addition('/student/add', 'POST')
})
addBtn.addEventListener('click', function () {
    $('#addModal').modal('show')
    btnCz.click()
    addModalLabel.innerHTML = '录入新学员'
    btnXg.innerHTML = '添加学员'
})
btnCz.addEventListener('click', function () {
    province.value = name.value = age.value = phone.value = salary.value = truesalary.value = group.value = ''
    county.innerHTML = `<option selected value="">--区--</option>`
    city.innerHTML = `<option selected value="">--市--</option>`
})
// 封装省市区以及删除请求函数
let provinces = (url, method, params, index, tally, label, callback) => {
    axios({
        url: url,
        method: method,
        params: params
    }).then(data => {
        if (data.code == 0) {
            init()
            toastr.success(data.message)
        } else if (data.code == 1) {
            toastr.error(data.message)
        } else {
            let str = '', newStr = '', arr = [], newArr = []
            data.forEach(value => {
                str += `<option value="${value}">--${value}--</option>`
                arr.push({ name: `<option value="${value}">--${value}--</option>` })
            })
            let obj = arr.filter(v => v.name == tally)[0]
            if (index == 1) {
                if (label) {
                    obj.name = label
                    arr.forEach(v => newArr.push(v.name))
                    str = newArr.join(' ')
                    callback()
                }
                newStr = `<option selected value="">--市--</option>` + str
                city.innerHTML = newStr
            } else if (index == 2) {
                if (label) {
                    obj.name = label
                    arr.forEach(v => newArr.push(v.name))
                    str = newArr.join(' ')
                }
                newStr = `<option selected value="">--区--</option>` + str
                county.innerHTML = newStr
            } else {
                newStr = `<option selected value="">--省--</option>` + str
                province.innerHTML = newStr
            }
        }
    })
}
provinces('/geo/province', 'GET')
province.addEventListener('change', function () {
    city.innerHTML = `<option selected value="">--市--</option>`
    county.innerHTML = `<option selected value="">--区--</option>`
    if (province.value == '') return
    let params = { pname: province.value }
    provinces('/geo/city', 'GET', params, 1)
})
city.addEventListener('change', function () {
    county.innerHTML = `<option selected value="">--区--</option>`
    if (city.value == '') return
    let params = { pname: province.value, cname: city.value }
    provinces('/geo/county', 'GET', params, 2)
})
// 事件委托：修改和删除按钮
tbody.addEventListener('click', function (e) {
    if (e.target.classList.contains('delete')) {
        if (confirm('是否删除')) {
            let params = { id: e.target.dataset.id }
            provinces('/student/delete', 'DELETE', params)
        }
    } else if (e.target.classList.contains('btn-primary')) {
        axios({
            url: '/student/one',
            method: 'GET',
            params: { id: e.target.dataset.id }
        }).then(({ data }) => {
            addModalLabel.innerHTML = '修改学员'
            btnXg.innerHTML = '确认修改'
            id = e.target.dataset.id
            $('#addModal').modal('show')
            age.value = data.age
            name.value = data.name
            truesalary.value = data.truesalary
            salary.value = data.salary
            phone.value = data.phone
            id = data.id
            group.value = data.group
            data.sex == '男' ? document.querySelectorAll('[name="sex"]')[0].checked = true : document.querySelectorAll('[name="sex"]')[1].checked = true
            id = e.target.dataset.id
            province.value = data.province
            let params = { pname: data.province }, tally = `<option value="${data.city}">--${data.city}--</option>`, label = `<option selected value="${data.city}">--${data.city}--</option>`
            let callback = () => {
                let params = { pname: data.province, cname: data.city }, tally = `<option value="${data.county}">--${data.county}--</option>`, label = `<option selected value="${data.county}">--${data.county}--</option>`
                provinces('/geo/county', 'GET', params, 2, tally, label)
            }
            provinces('/geo/city', 'GET', params, 1, tally, label, callback)
            $('#addModal').modal('show')
            addModalLabel.innerHTML = '修改学员'
            btnXg.innerHTML = '确认修改'
        })
    }
})
